package com.sqly.doc.menu.fwjl;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.PopupMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.camera.CameraChoose;
import com.sqly.doc.menu.fjh.fjh_list;
import com.sqly.doc.menu.fjh.fjhdycrhsf;
import com.sqly.doc.menu.fjh.fjhsf;
import com.sqly.doc.pojo.FjhDycrhsf;
import com.sqly.doc.pojo.FjhSf;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServiceRecord;
import com.sqly.doc.pojo.SignUp;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.CustomDatePicker;
import com.sqly.doc.view.StringUtils;
import com.sqly.doc.view.XListView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cz.msebera.android.httpclient.Header;

/**
 * 服务记录列表
 * Created by Administrator on 2020/02/14 0028.
 */

public class fwjl_list extends MyBaseActivity {
    XListView listView;
    //标题
    TextView title, uname;
    LinearLayout back;
    ZLoadingDialog dialog;//加载动画
    Context con = fwjl_list.this;
    private int pageNum1 = 1;// 无关键字页数
    List<ServiceRecord> list;
    private ImageView cx;
    private TextView key;
    String signupid = "",jmname = "", signuptime="", jkdah="";
    private CustomDatePicker customDatePicker;

    @Override
    protected void initUI() {
        setContentView(R.layout.fwjl_list);
        SignUp signUp = (SignUp) getIntent().getExtras().getSerializable("b");
        if(null != signUp) {
            signupid = signUp.getUid();
            jmname = signUp.getParty_b_name();
            signuptime= signUp.getTbtime();
            jkdah= signUp.getParty_b_id();
        }
        cx = (ImageView) findViewById(R.id.cx);
        cx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNum1 = 1;
                getData();
            }
        });
        key = (TextView) findViewById(R.id.key);
        key.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        key.setText(time.split(" ")[0]);
                    }
                }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show(now);
            }
        });
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("居民“"+signUp.getParty_b_name()+"”服务记录");
        uname.setText("新增");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(con, fwjl_add.class).putExtra("type", "add").putExtra("signupid", signupid).putExtra("signuptime", signuptime).putExtra("jkdah", jkdah));
            }
        });
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Bundle b = new Bundle();
//                b.putSerializable("b", list.get(i - 1));
//                startActivity(new Intent(con, fwjl_add.class).putExtras(b).putExtra("type", "edit").putExtra("signupid", signupid));
                showPopupMenu(view, i);
            }
        });
    }

    PopupMenu popupMenu;
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("RestrictedApi")
    private void showPopupMenu(View view, final int position ) {
        // View当前PopupMenu显示的相对View的位置
        popupMenu = new PopupMenu(fwjl_list.this, view, Gravity.END);
        // menu布局
        popupMenu.getMenuInflater().inflate(R.menu.list_menu, popupMenu.getMenu());
        // menu的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Bundle b = new Bundle();
                b.putSerializable("b", list.get(position - 1));
                if(item.getItemId() == R.id.item_edit){
                    startActivity(new Intent(con, fwjl_add.class).putExtras(b).putExtra("type", "edit").putExtra("signupid", signupid).putExtra("signuptime", signuptime).putExtra("jkdah", jkdah));
                }else if(item.getItemId() == R.id.item_fyyw){
                    startActivity(new Intent(con, fwjl_yw_list.class).putExtras(b).putExtra("type", "edit").putExtra("signupid", signupid).putExtra("flag", 1));
                }else if(item.getItemId() == R.id.item_zjpc){
                    startActivity(new Intent(con, fwjl_yw_list.class).putExtras(b).putExtra("type", "edit").putExtra("signupid", signupid).putExtra("flag", 2));
                }else if(item.getItemId() == R.id.item_zjjl){
                    startActivity(new Intent(con, fwjl_yw_list.class).putExtras(b).putExtra("type", "edit").putExtra("signupid", signupid).putExtra("flag", 3));
                }else if(item.getItemId() == R.id.item_ghyw){
                    startActivity(new Intent(con, fwjl_yw_list.class).putExtras(b).putExtra("type", "edit").putExtra("signupid", signupid).putExtra("flag", 4));
                }
                return false;
            }
        });

        // PopupMenu关闭事件
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                //Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
            }
        });
        //使用反射，强制显示菜单图标
        try {
            Field field = popupMenu.getClass().getDeclaredField("mPopup");
            field.setAccessible(true);
            MenuPopupHelper mHelper = (MenuPopupHelper) field.get(popupMenu);
            mHelper.setForceShowIcon(true);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        popupMenu.show();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetWorkUtils.isNetworkConnected(con)) {//联网状态
            getData();
        }
    }

    @Override
    protected void initListener() {

    }

    public void getData() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");

        ps.add("signupid",signupid);
        if (!StringUtils.isEmpty(key.getText().toString()))
            ps.add("sj", key.getText().toString());
        UserClient.get(HttpUrl.GetFwjlList, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    if (pageNum1 == 1)
                        list = new ArrayList<ServiceRecord>();
                    List<ServiceRecord> ll = JSON.parseArray(ret.getList(), ServiceRecord.class);
                    JSONArray js = JSON.parseArray(ret.getList());
                    for (int i = 0; i < js.size(); i++) {
                        JSONObject j = js.getJSONObject(i);
                        ll.get(i).setSrid(j.getString("id"));
                    }
                    for (int i = 0; i < ll.size(); i++) {
                        list.add(ll.get(i));
                    }

                    listView.setSelection(list.size() - ll.size());
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    listView.setRefreshTime("刚刚");
                    listView.setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                            pageNum1 = 1;
                            getData();
                        }

                        @Override
                        public void onLoadMore() {
                            pageNum1 = pageNum1 + 1;
                            getData();
                        }
                    });
                    listView.setAdapter(new CommonAdapter<ServiceRecord>(con, list, R.layout.fwjh_item) {
                        @Override
                        public void convert(ViewHolder helper, ServiceRecord item) {
                            helper.setText(R.id.sj, "服务时间:"+DateConvert.dateToString(DateConvert.toDate(item.getWork_time(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            helper.setText(R.id.fwnr, "症状:" + item.getZz_name());
                            helper.setText(R.id.jm, "居民:" + jmname);
                        }
                    });
                } else {
                    MyToastUtil.ShowToast(con, "获取错误");
                }
            }
        });
    }
}
